package com.hashmaptest;

import sun.misc.Unsafe;

import java.lang.reflect.Field;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;

/**
 * @author yaochenglong
 * @version V1.0
 * @date 2020/10/27 19:39
 * @DESC
 */
public class Test {

    public static void main(String[] args) throws NoSuchFieldException, IllegalAccessException {
//        long currentTimeMillis = System.currentTimeMillis();
//        int a=0;
//        int times = 10000*10000;
//        for (long i = 0; i < times; i++) {
//            a=9999%1024;
//        }
//        long currentTimeMillis2 = System.currentTimeMillis();
//
//        int b=0;
//        for (long i = 0; i < times; i++) {
//            b=9999&(1024-1);
//        }
//
//        long currentTimeMillis3 = System.currentTimeMillis();
//        System.out.println(a+","+b);
//        System.out.println("%: "+(currentTimeMillis2-currentTimeMillis));
//        System.out.println("&: "+(currentTimeMillis3-currentTimeMillis2));
        //testThreshold();
        //testPut();
        //capacityAdjustment();
        //System.out.println(Integer.highestOneBit(16));
        //testRedBlackTransfer();
        //testCHashMap();
        testUnsafe();
    }

    public static void testCHashMap(){
        ConcurrentHashMap cmap = new ConcurrentHashMap(10,8,9);
        cmap.put("1",1);
    }

    public static void testThreshold(){
        Map map = new HashMap(4,200);
        for (int i = 0; i < 500; i++) {
            map.put(i,i);
        }
        Object o = map.get(4);
        System.out.println(o);
    }

    public static void testRedBlackTransfer(){
        Map<User,User> map = new HashMap(4,1);
        for (int i = 1; i <= 500; i++) {
            User user = new User(i,i+"abc");
            map.put(user,user);
        }
        User user = new User(4,4+"abc");
        User o = map.get(user);
        System.out.println(o);
    }

    public static void testPut(){
        Map map = new HashMap();
        map.put("key","value");
        Object key = map.get("key");
        System.out.println(key);
    }

    public static void capacityAdjustment(){
        Map map = new HashMap(6);
        map.put("a","a");
        map.get("a");
    }

    public static void testUnsafe() throws NoSuchFieldException, IllegalAccessException {
        final Person p = new Person();
        Field f = Unsafe.class.getDeclaredField("theUnsafe");
        f.setAccessible(true);
        Unsafe unsafe = (Unsafe) f.get(null);
        int ns = unsafe.arrayBaseOffset(String[].class);
        int base = unsafe.arrayIndexScale(String[].class);
        System.out.println(unsafe.getObject(p.table,base+2*ns));
    }
}
